"""
搜索视图 - 门户网站
"""

from rest_framework.views import APIView
from rest_framework.response import Response
from pecco_site.models import Product


class SearchView(APIView):
    """
    搜索 API
    
    GET /api/shop/search/?q=&locale=en
    """
    permission_classes = []  # 公开访问
    
    def get(self, request):
        locale = request.GET.get('locale', 'en')
        query = request.GET.get('q', '')
        
        if not query:
            return Response({'results': []})
        
        # 在产品名称和描述中搜索
        products = Product.objects.filter(
            is_active=True,
            translations__locale=locale,
            translations__name__icontains=query
        ).distinct()[:10]
        
        results = []
        for prod in products:
            translation = prod.translations.filter(locale=locale).first()
            if translation:
                # 获取封面图
                first_image = prod.images.first()
                cover_url = request.build_absolute_uri(first_image.image.url) if first_image and first_image.image else None
                
                results.append({
                    'id': prod.id,
                    'name': translation.name,
                    'short_desc': translation.short_desc or '',
                    'cover': cover_url,
                })
        
        return Response({'results': results})

